package com.example.mybatisplus01.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;

import com.example.mybatisplus01.bean.User;
import com.example.mybatisplus01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * Crestes bylenovo on 2025/3/18
 */

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // Create
    @PostMapping
    public boolean createUser(@RequestBody User user) {
        return userService.save(user);
    }

    // Read
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }

    @GetMapping
    public List<User> getAllUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        return userService.list(queryWrapper);
    }

    // Update
    @PutMapping("/{id}")
    public boolean updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        User user = userService.getById(id);
        user.setUsername(userDetails.getUsername());
        user.setAddress(userDetails.getAddress());
        return userService.updateById(user);
    }

    // Delete
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }
}